<?php

namespace App\Controller\App;

use App\Base\BaseCache;
use App\Base\BaseController4Restful;
use App\Base\Format;
use App\Entity\Money;
use App\Entity\MoneyFreezeLog;
use App\Entity\User;
use App\Model\LazyCommon\UserModel;
use App\Repository\CategoryRepository;
use App\Repository\ConfigRepository;
use App\Repository\MoneyCashLogRepository;
use App\Repository\MoneyRepository;
use App\Repository\MoneyStaticRepository;
use App\Repository\MoneyTypeRepository;
use App\Repository\PlatPayCardRepository;
use App\Repository\PlatPayCodeRepository;
use App\Service\MoneyService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use function Doctrine\ORM\QueryBuilder;

/**
 * @route("/app")
 */
class UserMoneyController extends BaseController4Restful
{
    /**
     * @Route("/user/money", name="AppUserMoney")
     */
    public function AppUserMoney(MoneyService $moneyService,ConfigRepository $configRepository)
    {
        $user = $this->getUser();
        //获取用户现有资金
        $money = $moneyService->getUserMoney($user);

//        //获取平台数据
//        //1.年化收益
//        $rate = $configRepository->getByK("INCOME_RATE_YEAR");
//        $money["rate"] = $rate;//年化收益
//        $money["incomeDay"] = round(( $money["xuni"] + $money["guquan"] ) * $rate / 365 / 100,6);//年化收益下每天的收益值
//        //2.平台股权
//        $money["platGuquan"] = round($moneyService->getPlatGuQuan(),6);
//        //3.今日分红池
//        $money["platFenhong"] = round( $moneyService->getBonusPoolByDay() , 6);
//        //--用户分红预计//todo 还没有加入时间日期考虑的问题
//        $money["userFenhong"] = $moneyService->calcUserFenHong($user, $money["platGuquan"],$money["platFenhong"]);
//        $money["userFenhong"] = round($money["userFenhong"] ,6);

        return $this->json_out(200,"数据获取成功",$money);
    }
    /**
     * @Route("/user/devCharge", name="devCharge")
     */
    public function devCharge(MoneyService $moneyService)
    {
        if(!$money = $this->getParamRequired("money")){return $this->json_out(400,"请输入充值金额");}
        $user = $this->needToBeUser();
        $money = $moneyService->mod($user,$money * 10,MoneyService::__MONEY_JI_FEN__,101,"现金充值测试",["test"]);
        return $this->json_out(200,"数据获取成功",$money);
    }

    /**
     * @Route("/user/money/move", name="AppUserMoneyMove")
     */
    public function AppUserMoneyMove(MoneyService $moneyService)
    {
        $user = $this->getUser();
        if(!$money = $this->getParamRequired("money")){return $this->json_out(400,"请输入充值金额");}
        $userMoney = $moneyService->getUserMoney($user);
        if ($userMoney["yue"] < $money) {
            return $this->json_out(400,"余额不足");
        }

        //扣除现金余额
        $moneyService->mod($user,$money*-1,MoneyService::__MONEY_XIAN_JIN__,220,"余额转出",["余额转出到增值账户"]);
        //增加积分余额
        $moneyService->mod($user,$money,MoneyService::__MONEY_XU_NI_BI__,120,"余额转入",["余额转入本账户"]);


        return $this->json_out(200,"数据获取成功",$money);
    }

    /**
     * @Route("/user/money/freeze", name="AppUserMoneyFreeze")
     */
    public function AppUserMoneyFreeze(MoneyService $moneyService)
    {
        $user = $this->getUser();
        if(!$money = $this->getParamRequired("money")){return $this->json_out(400,"请输入充值金额");}
        $userMoney = $moneyService->getUserMoney($user);
        if ($userMoney["xuni"] < $money) {
            return $this->json_out(400,"余额不足");
        }
        //扣除理财余额
        $moneyService->mod($user,$money*-1,MoneyService::__MONEY_XU_NI_BI__,220,"增值余额转出",["增值账户转出到股权账户"]);
        //增加股权余额
        $moneyService->mod($user,$money,MoneyService::__MONEY_GU_QUAN__,120,"股权余额转入",["增值账户转入本账户"]);
        //增加冻结表的数据统计moneyFreezeLog
        $MoneyFreezeLog = new MoneyFreezeLog();
        $MoneyFreezeLog->setMoney($money)
            ->setUser($user)
            ->setType($moneyService->moneyTypeRepository->find(MoneyService::__MONEY_GU_QUAN__))
            ->setStartAt(new \DateTime())
            ->setFlag(MoneyService::__FREEZE_GU_QUAN__);
        $this->myEm()->persist($MoneyFreezeLog);
        $this->myEm()->flush();

        return $this->json_out(200,"数据获取成功",$money);
    }


    /**
     * @Route("/user/money/back", name="AppUserMoneyBack")
     */
    public function AppUserMoneyBack(MoneyService $moneyService)
    {
        $user = $this->getUser();
        if(!$money = $this->getParamRequired("money")){return $this->json_out(400,"请输入充值金额");}
        $userMoney = $moneyService->getUserMoney($user);
        if ($userMoney["xuni"] < $money) {
            return $this->json_out(400,"余额不足");
        }

        //扣除现金余额
        $moneyService->mod($user,$money,MoneyService::__MONEY_XIAN_JIN__,220,"增值账户转出到余额",["增值账户转出到余额"]);
        //增加积分余额
        $moneyService->mod($user,$money*-1,MoneyService::__MONEY_XU_NI_BI__,120,"增值账户转出到余额",["增值账户转出到余额"]);


        return $this->json_out(200,"数据获取成功",$money);
    }

    /**
     * @Route("/user/money/unfreeze", name="AppUserMoneyUnFreeze")
     */
    public function AppUserMoneyUnFreeze(MoneyService $moneyService)
    {
        $user = $this->getUser();
        if(!$money = $this->getParamRequired("money")){return $this->json_out(400,"请输入充值金额");}
        $userMoney = $moneyService->getUserMoney($user);
        if ($userMoney["guquan"] < $money) {
            return $this->json_out(400,"余额不足");
        }
        //扣除理财余额
        $moneyService->mod($user,$money,MoneyService::__MONEY_XU_NI_BI__,220,"分红账户解冻",["增值账户转出到股权账户"]);
        //增加股权余额
        $moneyService->mod($user,$money*-1,MoneyService::__MONEY_GU_QUAN__,120,"分红账户解冻",["增值账户转入本账户"]);
        //从冻结列表中删除数据
        $moneyService->deleteFreezeGuQuan($user,$money);
        return $this->json_out(200,"数据获取成功",$money);
    }



    /**
     * @Route("/user/money/card/get", name="AppUserMoneyCardGet")
     */
    public function AppUserMoneyCardGet(MoneyService $moneyService)
    {
        $user = $this->needToBeUser();
        $cads = $user->getMoneyCards();
        if ($cads->count() == 0) {
            return $this->json_out(200,"","");
        }else{
            $card = $cads->getValues()[0];
            return $this->json_out(200,"",$card);
        }
    }
    /**
     * @Route("/plat/money/card/get", name="AppPlatMoneyCardGet")
     */
    public function AppPlatMoneyCardGet(PlatPayCardRepository $cardRepository ,PlatPayCodeRepository $codeRepository)
    {
        $user = $this->needToBeUser();
        $data["phone"] = $user->getPhone();
        $data["cards"] = $cardRepository->findBy(array("status"=>1),array("sort"=>"ASC"));
        $data["codes"] = $codeRepository->findBy(array("status"=>1),array("sort"=>"ASC"));

        return $this->json_out(200,"",$data);
    }

    /**
     * @Route("/user/money/cash", name="AppUserMoneyCash")
     */
    public function AppUserMoneyCash(MoneyService $moneyService)
    {
        $user = $this->needToBeUser();
        if(!$money = $this->getParamRequired("money")){
            return $this->json_out(201,"请输入提现金额");
        }
        $userMoney = $moneyService->getUserMoney($user);
        if ($userMoney["yue"] < $money) {
            return $this->json_out(201,"余额不足",$userMoney);
        }
        $card = $user->getMoneyCards()->getValues()[0]??null;
        if (!$card) {
            return $this->json_out(201,"请绑定提现银行卡",$card);
        }
        $moneyService->userCash($user,$money);
        return $this->json_out(200,"提现成功");
    }




    /**
     * @Route("/user/money/cash/log", name="AppUserMoneyCashLog")
     */
    public function AppUserMoneyCashLog(MoneyCashLogRepository $repository)
    {
        $user = $this->needToBeUser();
        if(!$page = $this->getParamRequired("page")){$page = 1;}
        $list = $repository->findBy(array("user"=>$user),array("id"=>"DESC"),10,($page - 1)*10);
        return $this->json_out(200,"列表获取成功",$list);
    }
    

    /**
     * @Route("/user/money/log", name="AppUserMoneyLog")
     */
    public function AppUserMoneyLog(MoneyService $moneyService)
    {
        $user = $this->needToBeUser();
        if(!$type = $this->getParamRequired("type")){return $this->json_out(0,"请求参数缺失");}
        if(!$flag = $this->getParamRequired("flag")){$flag = 0;}
        if(!$page = $this->getParamRequired("page")){$page = 1;}
        switch ($type) {
            case "fenhong":
                $list = $moneyService->getUserLog($user,MoneyService::__MONEY_XU_NI_BI__,151,$page);
                break;
            case "zengzhi":
                $list = $moneyService->getUserLog($user,MoneyService::__MONEY_XU_NI_BI__,150,$page);
                break;
            case "yue":
                $list = $moneyService->getUserLog($user,MoneyService::__MONEY_XIAN_JIN__,0,$page);
                break;
            case "xuni":
                $list = $moneyService->getUserLog($user,MoneyService::__MONEY_XU_NI_BI__,0,$page);
                break;
            case "guquan":
                $list = $moneyService->getUserLog($user,MoneyService::__MONEY_GU_QUAN__,0,$page);
                break;
            case "jifen":
                $list = $moneyService->getUserLog($user,MoneyService::__MONEY_JI_FEN__,$flag,$page);
                break;
            default:
                $list = array();
        }
        return $this->json_out(200,"数据获取成功",$list);

    }

    /**
     * @Route("/money/exchange", name="AppMoneyExchange")
     */
    public function AppMoneyExchange(MoneyService $moneyService,ConfigRepository $configRepository,MoneyRepository $moneyRepository)
    {
        $user = $this->needToBeUser();
        $userMoney = $moneyService->getUserMoney($user);
        $jf = $userMoney["jifen"];
        $rate = $configRepository->getByK("MONEY_EXCHANGE_RATE");
        $data["jifen"] = $jf;
        $data["canBuy"] = round($jf/$rate,3);

        $qb = $moneyRepository->createQueryBuilder("A");
        $qb->where("A.type = ".MoneyService::__MONEY_GU_QUAN__);
        $qb->setFirstResult(0)->setMaxResults(3);
        $qb->orderBy("A.money","DESC");

        $rank = $qb->getQuery()->execute();
        $data["rank"] = $rank;
        $this->setGroups("user","money");
        return $this->json_out(200,"OK",$data);
    }
    /**
     * @Route("/user/money/exchange", name="AppUserMoneyToGuquan")
     */
    public function AppUserMoneyToGuquan(MoneyService $moneyService
        ,ConfigRepository $configRepository
        ,MoneyRepository $moneyRepository
        ,MoneyStaticRepository $moneyStaticRepository
        ,MoneyTypeRepository $moneyTypeRepository
    )
    {
        if(!$money = $this->getParamRequired("money")){return $this->json_out(400,"请输入积分数量");}
        $user = $this->needToBeUser();
        if (!$user->getIdcard()) {
            return $this->json_out(400,"请先完成实名认证","renzheng");
        }

        $qb = $moneyRepository->createQueryBuilder("A");
        $qb->select("sum(A.money) as total")
            ->where("A.type = ".MoneyService::__MONEY_GU_QUAN__);
        $rst = $qb->getQuery()->execute();
        $total = $rst[0]["total"];

        $max = $configRepository->getByK("PLAT_PERCENT_TOTAL");



        if ($total >= $max) {
            return $this->json_out(400,"您来晚了，股权已全部兑换");
        }


        //检查 161 160

//        $moneyStaticRepository->getUserMoneyStaticByType($user,$moneyTypeRepository->find(MoneyService::__MONEY_JI_FEN__),160);
        $qb = $moneyStaticRepository->createQueryBuilder("A");
        $qb->select("sum(A.money) as money")
            ->where("A.user = {$user->getId()}")
            ->andWhere("A.moneyType = ".MoneyService::__MONEY_JI_FEN__)
            ->andWhere($qb->expr()->in("A.logType",[161,160]));

        $data = $qb->getQuery()->execute();
        $total = $data[0]["money"];
        $usermoney = $moneyRepository->findOneBy(array("user"=>$user,"type"=>$moneyTypeRepository->find(2)));
        if (!$usermoney) {
            $total = 0;
        }else{
            $total = $usermoney->getMoney();
        }


        $min = $configRepository->getByK("GUQUAN_GET_LIMIT_JIF");
        if ($total < $min) {
            return $this->json_out(400,"推广积分不足不能兑换");
        }
//        dd();

        $conf = $configRepository->findAll();
        $config = [];
        foreach ($conf as $row) {
            $config[$row->getK()] = $row->getV();
        }
        //保证金支付金额设置
        $exchange = $config["MONEY_EXCHANGE_RATE"];

        $jf = $moneyService->getUserMoney($user)["jifen"];
        if ($money * $exchange > $jf) {
            return $this->json_out(400,"积分不足");
        }


        $jifen = $money * $exchange;
        $guquan = (float)$money ;

        $moneyService->mod($user,$jifen * -1,MoneyService::__MONEY_JI_FEN__,221,"兑换股权");
        $moneyService->mod($user,$guquan * 1,MoneyService::__MONEY_GU_QUAN__,121,"兑换股权");

        return $this->json_out(200,"兑换成功",[]);
    }


    /**
     * @Route("/plat/money", name="AppPlatMoney")
     */
    public function AppPlatMoney(
        MoneyRepository $moneyRepository,
        ConfigRepository $configRepository
    )
    {
        $qb = $moneyRepository->createQueryBuilder("A");
        $qb->select("sum(A.money) as total")
            ->where("A.type = ".MoneyService::__MONEY_GU_QUAN__);
        $rst = $qb->getQuery()->execute();
        $total = $rst[0]["total"];

        $totalPlat = $configRepository->getByK("PLAT_PERCENT_TOTAL");


        return $this->json_out(200,"获取成功",$totalPlat-(int)$total);
    }
}
